
from  langchain_core.tools import tool
from  langchain.tools.render import render_text_description
from langchain_core.output_parsers import JsonOutputParser,StrOutputParser
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from operator import itemgetter
from langchain_core.runnables import RunnablePassthrough,RunnableLambda,Runnable
from typing import  Union

import requests
import json
import time
# 将json字符串解析成python的dict
parser = JsonOutputParser()


apiKey = 'ba07d2a01027fa521b4423713080d8e2'  # 在个人中心->我的数据,接口名称上方查看
@tool
def tianqi(city:str) -> dict:
    "查询城市的天气，湿度，温度，风向大小"
    # 接口请求入参配置
    requestParams = {
        'key': apiKey,
        'city': city,
    }
    apiUrl = 'http://apis.juhe.cn/simpleWeather/query'  # 接口请求URL
    headers={
        "content-type":"application/x-www-form-urlencoded"
    }
    # 发起接口网络请求
    response = requests.get(apiUrl, params=requestParams,headers=headers)

    # 解析响应结果
    if response.status_code == 200:
        # responseResult = response.json()
        responseResult = json.loads(response.text)
        # 网络请求成功。可依据业务逻辑和接口文档说明自行处理。
        # print(responseResult)
        return responseResult
    else:
        # 网络异常等因素，解析结果异常。可依据业务逻辑自行处理。
        print('请求异常')
        return '请求异常'


@tool
def multiply(first_int: int, second_int: int) -> int:
    """Multiply two integers together.求两数的乘积"""
    return first_int * second_int


@tool
def add(first_int: int, second_int: int) -> int:
    "Add two integers.求两数之和"
    return first_int + second_int


@tool
def exponentiate(base: int, exponent: int) -> int:
    "Exponentiate the base to the exponent power.求一个数的幂"
    return base**exponent

tools=[multiply,add,exponentiate,tianqi]

# def tool_chain(model_input):
#     tool_map={tool.name:tool for tool in tools }
    
#     choose_tool = tool_map[model_input["name"]]
#     print(choose_tool)
#     return itemgetter("arguments") | choose_tool

# tianqi.invoke({"city":'南京'})
tool_des=render_text_description(tools)
 
ZHIPUAI_API_KEY = '794380a4cee054a0f96bb2844b41fd12.X4t70kph1CfmoKfT'
BASE_PATH ='https://open.bigmodel.cn/api/paas/v4/'

model = ChatOpenAI(model_name='glm-4',temperature=.7,openai_api_key=ZHIPUAI_API_KEY,base_url=BASE_PATH)
current_date = time.strftime("%Y-%m-%d",time.localtime())
 
systemPrompt = f"""您是一名助理，可以从下面工具中选择多个或一个来完成任务，以下是这些工具的说明：
    {tool_des}
    今天是{current_date},根据用户输入，返回所有解决问题所需的使用的工具的名称和输入，按照执行顺序，将您的响应作为带有name和arguments键的json blob 返回,不要有其他任何文字,此json blob 格式为```json ... ```"""
prompt = ChatPromptTemplate.from_messages(
    [
        ("system",systemPrompt),
        ("user","{input}")
    ]
)
template_tianqi = """
    根据下面问题和json格式的响应编写一个针对此问题的自然语言回应：
    问题：{question}
    响应：{response}
"""
# tool_map={tool.name:tool for tool in tools }

 
 
def tool_chain(model_input):
    tool_map={tool.name:tool for tool in tools } 
    choose_tool = tool_map[model_input["name"]] 
    print('1111111')
    print(model_input)  
    return  RunnablePassthrough.assign(output=itemgetter("arguments") | choose_tool)

call_tool_list = RunnableLambda(tool_chain).map()

prompt_response = ChatPromptTemplate.from_template(template_tianqi)
chain = {"input":RunnablePassthrough()}| prompt | model  
# print(chain.invoke({input:"What's 23 times 7, and what's five times 18 and add a million plus a billion and cube  thirty-seven"}).content)

# print(chain.invoke({input:"3+3*8+9"}).content)
print(chain.invoke({input:"3乘以8加9"}).content)
# chain = {"input":RunnablePassthrough()}| prompt | model | parser | tool_chain
# chain = {"input":RunnablePassthrough()}| prompt | model | parser | call_tool_list
chain1={"question":RunnablePassthrough(),"response":chain} | prompt_response | model 
# print(chain1.invoke("明天桂林出门穿什么衣服合适").content)
# print(chain1.invoke("What's 23 times 7, and what's five times 18 and add a million plus a billion and cube thirty-seven").content)

 
 
# from langchain_core.prompts import  PromptTemplate,FewShotPromptTemplate
# from langchain_openai import ChatOpenAI,OpenAIEmbeddings
# from langchain_core.output_parsers import StrOutputParser
# from langchain_community.vectorstores import FAISS
# from langchain_core.example_selectors import SemanticSimilarityExampleSelector




# parser = StrOutputParser()
 

# model = ChatOpenAI(model_name='glm-4',temperature=.7,openai_api_key=ZHIPUAI_API_KEY,base_url=BASE_PATH)

# example_prompt = PromptTemplate(input_variables=["input","output"],template="示例输入：{input},输出：{output}")
# examples = [
#     {"input":"海盗","output":"船"},
#     {"input":"飞行员","output":"飞机"},
#     {"input":"驾驶员","output":"汽车"},
#     {"input":"树","output":"地面"},
#     {"input":"鸟","output":"鸟巢"}
# ]
 
# pip install tiktoken
# pip install faiss-cpu
# example_selector = SemanticSimilarityExampleSelector.from_examples(
#     examples,
#     OpenAIEmbeddings(openai_api_key=ZHIPUAI_API_KEY,base_url=BASE_PATH),
#     FAISS,
#     k=2
# )
# similar_prompt = FewShotPromptTemplate(
#     example_selector=example_selector,
#     examples=examples,
#     example_prompt=example_prompt,
#     prefix="根据下面示例写出输出",
#     suffix="你的输入：{what}，输出：",
#     input_variables=["what"],
#     example_separator=" "
# )
# what = "学生"
# print(similar_prompt.format(what=what))
# print(model.invoke(similar_prompt.format(what=what)).content)













 
# MOONSHOT_API_KEY = "sk-frDCb3ceOG9aot1alISE2XJrXzeb3utkWXrrIrqZiYOH2kLq"
# chat = ChatOpenAI(model_name='moonshot-v1-8k',temperature=.7,openai_api_key=MOONSHOT_API_KEY,base_url='https://api.moonshot.cn/v1/')

# print(f"模板输出 {chat.invoke(finalPrompt)}"
# )
# from zhipu import ZhipuAI
# from langchain.chat_models import ChatOpenAI
# from langchain.schema import SystemMessage,HumanMessage,AIMessage
#  Importing PromptTemplate from langchain root module is no longer supported
# from langchain import PromptTemplate

# template = "我很想去{location}旅行，我应该去哪里做什么"
# prompt = PromptTemplate(input_variables=["location"],template=template)
# finalPrompt = prompt.format(location="广东深圳")
# print(f'最终模板:{finalPrompt}')
# chat.invoke(
#     [SystemMessage('你是一个粤菜点餐人工智能助手，可以帮助用户在一个简单句子中明白用户想吃什么'),
#      HumanMessage('我喜欢吃西红柿，我应该吃什么')
     
#      ])
